<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'mo:tl:MoOrderApplyH:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #moOrderReturnCList>
        <BasicTable
          @register="registerMoOrderReturnCTable"
          @row-click="handleMoOrderReturnCRowClick"
        />
        <a-button class="mt-2" @click="handleMoOrderReturnCAdd" v-auth="'mo:tl:MoOrderApplyH:edit'">
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="tl_apply"
        completeText="提交"
        :loading="loadingRef"
        :auth="'mo:tl:MoOrderApplyH:edit'"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsMoTlMoOrderApplyHForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BpmButton } from '/@/components/Bpm';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    MoOrderApplyH,
    MoOrderApplyHSave,
    MoOrderApplyHForm,
  } from '/@/api/wms/mo/tl/MoOrderApplyH';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('mo.tl.MoOrderApplyH');
  const { showMessage } = useMessage();
  const record = ref<MoOrderApplyH>({} as MoOrderApplyH);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增退料申请') : t('编辑退料申请'),
  }));

  const loadingRef = ref(false);

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('存货编码'),
      field: 'cinvcode',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('存货名称'),
      field: 'cinvcode',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('部门编码'),
      field: 'mdeptcode',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('部门名称'),
      field: 'mdeptname',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    // {
    //   label: t('来源ID'),
    //   field: 'sourceid',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 100,
    //   },
    // },
    {
      label: t('备注'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('退料明细'),
      field: 'moOrderReturnCList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'moOrderReturnCList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 12 },
  });

  const [registerMoOrderReturnCTable, moOrderReturnCTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleMoOrderReturnCDelete.bind(this, record),
          },
          auth: 'mo:tl:MoOrderApplyH:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setMoOrderReturnCTableData(_res: Recordable) {
    moOrderReturnCTable.setColumns([
      {
        title: t('存货编码'),
        dataIndex: 'cinvcode',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: true,
      },
      {
        title: t('存货名称'),
        dataIndex: 'cinvname',
        width: 200,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: true,
      },
      {
        title: t('规格型号'),
        dataIndex: 'cinstd',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: false,
      },
      {
        title: t('仓库编码'),
        dataIndex: 'cwhcode',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: true,
      },
      {
        title: t('仓库名称'),
        dataIndex: 'basWare.cwhname',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: true,
      },
      {
        title: t('货位编码'),
        dataIndex: 'poscode',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('批次'),
        dataIndex: 'cbatch',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('退料数量'),
        dataIndex: 'iqty',
        width: 130,
        align: 'right',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 51,
        },
        editRule: true,
      },
    ]);
    moOrderReturnCTable.setTableData(record.value.moOrderReturnCList || []);
  }

  function handleMoOrderReturnCRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleMoOrderReturnCAdd() {
    moOrderReturnCTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleMoOrderReturnCDelete(record: Recordable) {
    moOrderReturnCTable.deleteTableDataRecord(record);
  }

  async function getMoOrderReturnCList() {
    let moOrderReturnCListValid = true;
    let moOrderReturnCList: Recordable[] = [];
    for (const record of moOrderReturnCTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        moOrderReturnCListValid = false;
      }
      moOrderReturnCList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of moOrderReturnCTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      moOrderReturnCList.push({
        ...record,
        status: '1',
      });
    }
    if (!moOrderReturnCListValid) {
      throw { errorFields: [{ name: ['moOrderReturnCList'] }] };
    }
    return moOrderReturnCList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await MoOrderApplyHForm(data);
    record.value = (res.MoOrderApplyH || {}) as MoOrderApplyH;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setMoOrderReturnCTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      data.bpm = record.value.bpm; // 流程信息
      data.status = record.value.status; // 提交状态
      loadingRef.value = true;
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        code: record.value.code,
      };
      data.moOrderReturnCList = await getMoOrderReturnCList();
      // console.log('submit', params, data, record);
      const res = await MoOrderApplyHSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
